package com.tourting.demo.controller;

import com.tourting.demo.model.User;
import com.tourting.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:8081")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    @ResponseBody
    public UsersResponse getAllUsers(HttpServletRequest req) {
        return new UsersResponse(userService.getAllUsers());
    }

    @GetMapping("/show")
    @ResponseBody
    public UserResponse getUserById(HttpServletRequest req, long id) {
        User user = userService.getById(id);
        return new UserResponse(user);
    }

    @PostMapping("/save")
    @ResponseBody
    public BaseResponse save(HttpServletRequest req, @ModelAttribute User user) {
        boolean isSuccess = userService.save(user);
        return isSuccess ? new UserResponse(user) : new BaseResponse(-1);
    }

    @PostMapping("/update")
    @ResponseBody
    public BaseResponse update(HttpServletRequest req, @ModelAttribute User user) {
        boolean isSuccess = userService.update(user);
        return new BaseResponse(isSuccess ? 200 : -1);
    }

    @DeleteMapping("/remove")
    @ResponseBody
    public BaseResponse remove(HttpServletRequest req, long id) {
        boolean isSuccess = userService.remove(id);
        return new BaseResponse(isSuccess ? 200 : -1);
    }
}
